<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { computed, reactive, ref } from 'vue';

import { message } from 'ant-design-vue';

// 定义props
interface Props {
  visible: boolean;
  scenarios: any[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  scenarios: () => [],
});

// 定义emits
const emit = defineEmits<{
  save: [category: any];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const saving = ref(false);

// 表单数据
const formData = reactive({
  name: '',
  description: '',
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入场景名称', trigger: 'blur' }],
};

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 方法
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const categoryData = {
      ...formData,
      id: Date.now().toString(),
    };

    emit('save', categoryData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
  resetForm();
};

const resetForm = () => {
  formData.name = '';
  formData.description = '';
  formRef.value?.resetFields();
};
</script>

<template>
  <a-modal
    v-model:open="visible"
    title="添加自定类"
    width="500px"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item label="场景名称" name="name" required>
        <a-input
          v-model:value="formData.name"
          placeholder="请输入场景名称"
          size="large"
        />
      </a-form-item>
      <a-form-item label="场景描述" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="请输入场景描述"
          :rows="3"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="saving" @click="handleSave">
          保存
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<style scoped>
/* 样式可以根据需要添加 */
</style>
